package com.juku2024.juku.fragment

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.AlbumActivity
import com.juku2024.juku.R
import com.juku2024.juku.VideoDetailActivity
import com.juku2024.juku.adapter.HomeTabAdapter
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.model.HomeAdapterItem
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.viewmodel.MainViewModel
import com.juku2024.juku.widget.LoadingView

class HomeTabFragment : BaseFragment() {

    companion object {
        fun init(genreId: Long): HomeTabFragment {
            val fragment = HomeTabFragment()
            val bundle = Bundle()
            bundle.putLong("tabId", genreId)
            fragment.arguments = bundle
            return fragment
        }
    }
    private var page = 1
    private var version = 0L
    private var genreId = -1L
    // 是否还有下一页数据可以请求，默认有
    private var hasNextPage = true
    private val tabAdapter by lazy { HomeTabAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(requireActivity().viewModelStore, MainViewModel::class.java) }

    private lateinit var loadingView: LoadingView
    private lateinit var homeTabRecycler: RecyclerView

    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_home_tab, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        loadingView = rootView.findViewById(R.id.loadingView_home_tab)
        homeTabRecycler = rootView.findViewById(R.id.homeTabRecycler)

        val gridLayoutManager = WrapGridLayoutManager(requireContext(), 3)
        gridLayoutManager.spanSizeLookup =
            object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(pos: Int): Int {
                    val type = homeTabRecycler.adapter?.getItemViewType(pos)
                    return if (type == MainViewModel.TYPE_GRID) {
                        1
                    } else {
                        3
                    }
                }
            }
        homeTabRecycler.layoutManager = gridLayoutManager
        homeTabRecycler.itemAnimator = null
    }

    override fun bindEvent() {
        super.bindEvent()
        tabAdapter.setOnItemChildClickListener { _, childView, position ->
            val item = tabAdapter.data[position]
            if (childView.id == R.id.titleNext ||  childView.id == R.id.tv_home_more) {
                val intent = Intent(requireContext(), AlbumActivity::class.java)
                intent.putExtra("album_id", item.id)
                intent.putExtra("album_version", item.version)
                intent.putExtra("album_name", item.name)
                startActivity(intent)
            } else {
                if (TextUtils.isEmpty(item.url)) {
                    VideoDetailActivity.toVideoDetail(requireContext(), item.id, item.name)
                } else {
                    AppUtils.toWeb(item.url!!)
                }
            }

        }


        tabAdapter.loadMoreModule.setOnLoadMoreListener {
            loadMoreRecommend()
        }

    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        genreId = arguments?.getLong("tabId") ?: -1
//        LogC.e("HomeTab $genreId -> Init..." + "page=$page, version=$version, adapterSize:${tabAdapter.data.size}")
        if (tabAdapter.data.isEmpty()) {
            page = 1
            version = 0L
            doHttpGetRecommend()
        } else {
            loadingView.post {
                homeTabRecycler.adapter = tabAdapter
                if (!hasNextPage) {
                    tabAdapter.loadMoreModule.loadMoreEnd(true)
                }
            }
        }
    }


    private fun doHttpGetRecommend() {
        viewModel.doHttpRecommend(genreId, page, version, {
            if (isFragmentNotActive()) return@doHttpRecommend
            loadingView.hideLoading()
            if (it.datas.isNullOrEmpty()) {
                if (tabAdapter.data.isEmpty()) {
                    loadingView.showEmptyStatus(getString(R.string.category_list_empty))
                } else {
                    tabAdapter.loadMoreModule.loadMoreFail()
                }
                return@doHttpRecommend
            }
            homeTabRecycler.adapter = tabAdapter
            // 设置banner
            if (it.carousel?.isNotEmpty() == true && it.datas?.all { it.template != MainViewModel.TYPE_BANNER } == true) {
                val item = HomeAdapterItem()
                item.adapterType = MainViewModel.TYPE_BANNER
                item.carousel = it.carousel
                it.datas?.add(0, item)
            }
            // 设置推荐模块
            tabAdapter.setList(it.datas)
            if (it.nextVersion == -1L) { // 不在请求数据
                hasNextPage = false
                tabAdapter.loadMoreModule.loadMoreEnd()
            } else {
                page++
                version = it.nextVersion
            }
        }, {
            if (isFragmentNotActive()) return@doHttpRecommend
            loadingView.hideLoading()
            if (tabAdapter.data.isEmpty()) {
                loadingView.showErrorStatus(it, getString(R.string.retry)) {
                    loadingView.showLoading()
                    loadingView.postDelayed({
                        if (isFragmentNotActive()) return@postDelayed
                        doHttpGetRecommend()
                    }, 500)
                }
            } else {
                tabAdapter.loadMoreModule.loadMoreFail()
            }
        })
    }


    private fun loadMoreRecommend() {
        LogC.d("doHttpLoadMore...page=$page, version=$version")
        viewModel.doHttpRecommend(genreId, page, version, {
            if (isFragmentNotActive()) return@doHttpRecommend
            if (it.datas.isNullOrEmpty()) {
                tabAdapter.loadMoreModule.loadMoreEnd(true)
                return@doHttpRecommend
            }
            // 初始化tabAdapter
            tabAdapter.addData(it.datas!!)
            if (it.nextVersion == -1L) {
                hasNextPage = false
                tabAdapter.loadMoreModule.loadMoreEnd(true)
            } else {
                tabAdapter.loadMoreModule.loadMoreComplete()
                version = it.nextVersion
                page++
            }
        }, {
            if (isFragmentNotActive()) return@doHttpRecommend
            if (BaseApplication.isLimited) {
                tabAdapter.loadMoreModule.loadMoreEnd()
            } else {
                tabAdapter.loadMoreModule.loadMoreFail()
            }
        })
    }
}